<template>
  <div class="login-page">
    <div class="login-card">
      <div class="brand">
        <el-icon><School /></el-icon>
        <div>
          <h1>神话学院管理系统</h1>
          <p>简化校园管理流程，提升协作效率</p>
        </div>
      </div>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        @keyup.enter="handleSubmit"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            size="large"
            clearable
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            size="large"
            type="password"
            show-password
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-button
          type="primary"
          size="large"
          class="login-btn"
          :loading="loading"
          @click="handleSubmit"
        >
          {{ loading ? '登录中...' : '立即登录' }}
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, School } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const formRef = ref()
const loading = ref(false)

const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度 3-20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度 5-20 个字符', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 使用Promise的方式处理表单验证，避免Vue的异常处理机制干扰
  return new Promise((resolve) => {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        // 验证通过，执行登录
        loading.value = true
        console.log('开始调用登录API，数据:', form)
        userStore.login(form)
          .then((response) => {
            console.log('登录API调用成功，响应:', response)
            const redirect = route.query.redirect || '/dashboard'
            router.replace(redirect)
            resolve(true)
          })
          .catch((error) => {
            console.error('登录API调用失败:', error)
            ElMessage.error(error?.message || '登录失败，请稍后重试')
            resolve(false)
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        // 验证失败，不显示错误信息，因为Element Plus会自动显示
        resolve(false)
      }
    })
  })
}
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e6f4ff 0%, #ffffff 60%);
  padding: var(--spacing-xl);
}

.login-card {
  width: 380px;
  padding: var(--spacing-xl);
  border-radius: var(--radius-lg);
  background: var(--bg-card);
  box-shadow: var(--shadow-lg);
}

.brand {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-xl);
  align-items: center;

  h1 {
    margin: 0;
  }

  p {
    margin: 4px 0 0;
    color: var(--text-secondary);
  }

  .el-icon {
    font-size: 36px;
    color: var(--color-primary);
  }
}

.login-btn {
  width: 100%;
  margin-top: var(--spacing-md);
}
</style>
